package br.com.engine.fisica;

import java.awt.Point;
import java.awt.Rectangle;
import java.util.List;

import br.com.engine.componentes.GameObject;
import br.com.engine.componentes.Sprite;
import br.com.engine.input.KeyMap;

public final class Colisao 
{
    public static boolean validateMovment( GameObject obj, int vel, int nKey, List<GameObject> lmap )
    {
        int nx = obj.getPosition( ).getPositionPixel( ).x;
        int ny = obj.getPosition( ).getPositionPixel( ).y;
        
        if( nKey == KeyMap.UP.getKey( ) )
        {
            ny -= vel;
        }
        else if( nKey == KeyMap.DOWN.getKey( ) )
        {
            ny += vel;
        }
        else if( nKey == KeyMap.LEFT.getKey( ) )
        {
            nx -= vel;
        }
        else if( nKey == KeyMap.RIGHT.getKey( ) )
        {
            nx += vel;
        }
        
        if( lmap != null )
        {
        	for( GameObject go : lmap )
        	{
        		Sprite sp = go.getComponent( Sprite.class );
        		
        		if( inColision( go, sp, new Rectangle( nx, ny, sp.getWidth( ), sp.getHeight( ) ) ) )
        			return false;
        	}
        }
        
        return true;
    }
   
    public boolean blocked( )
    {
        return false;
    }
        
	public static boolean inColision( GameObject obj1, GameObject obj2 )
	{
		if( obj1 == null || obj2 == null )
			return false;
		
		Rectangle rec  = toRectangle( obj1, obj1.getComponent( Sprite.class ) );
		Rectangle rec2 = toRectangle( obj2, obj2.getComponent( Sprite.class ) );
		
		return rec.intersects( rec2 );
	}
	
	public static boolean inColision( GameObject obj, Sprite sp, Rectangle rect )
    {
        Rectangle rec  = toRectangle( obj, sp );
        Rectangle rec2 = rect;
        
        return rec.intersects( rec2 );
    }
	
	public static GameObject inColision( GameObject obj, List<GameObject> lobjs )
	{
		GameObject objcol = null;
		
		for( GameObject item : lobjs )
		{
			if( inColision( obj, item ) )
			{
				objcol = item;;
				break;
			}
		}
		
		return objcol;
	}
	
	public static Rectangle toRectangle( GameObject obj, Sprite sp )
	{
		Point pos = obj.getPosition( ).getPositionPixel( );
		
		return new Rectangle( pos.x, pos.y, sp.getWidth( ), sp.getHeight( ) );
	}
}